//
//  HomeTableViewController.swift
//  XDweibo
//
//  Created by HanXingda on 15/6/23.
//  Copyright © 2015年 韩兴达. All rights reserved.
//

import UIKit
import SVProgressHUD
class HomeTableViewController: BaseTableViewController,StatusCellDelegate {

    //定义模型数组
    var weiboArray:[Status]? {
        didSet {
            // 刷新表格
            tableView.reloadData()
           
        }
    }
    // 定义行高缓存 [statusId: 行高]
    lazy var rowHeightCache = [Int: CGFloat]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        vistorView?.setupViewInfo("visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
        
        if !login {
            print("必须登录后才能设置数据")
            return
        }
        
        //创建刷新控件refresh
        perpareRefreshControl()
        //创建cell
        perpareCell()
        //设置导航栏
        setupNavgationBar()
        //加载数据
        loadData()
        
    }
    
    func perpareRefreshControl() {
        refreshControl = XDrefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
}
    
    func perpareCell() {
        tableView.rowHeight = 300
        //注册可重用cell
        tableView.registerClass(NormalCell.self, forCellReuseIdentifier: XDNormalCellReuseIdentifier)
        tableView.registerClass(RetweetedCell.self, forCellReuseIdentifier: XDRetweetCellReuseIdentifier)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        vistorView?.startAnimation()
    }
    override func didReceiveMemoryWarning() {
        //清除缓存的行高
        rowHeightCache.removeAll()
    }
    //加载数据
    func loadData() {
        refreshControl?.beginRefreshing()
        //下拉刷新
       let since_id = weiboArray?.first?.id ?? 0
       var max_id = 0
        
        if PullRefreshFlag {
         since_id == 0
         //上拉刷新
        max_id = weiboArray?.last?.id ?? 0
        
        }
        
        Status.loadStatus(since_id,max_id: max_id) { (array, error) -> () in
            //关闭刷新控件
            self.refreshControl?.endRefreshing()
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            if array == nil {
                print("没有数据")
                return
            }
            //下拉刷新
            if since_id > 0 {
                self.weiboArray = array! + self.weiboArray!
            }else if max_id > 0{
                self.weiboArray = self.weiboArray! + array!
            } else {
                
                self.weiboArray = array
            }
        }

        }
    
       // MARK: - StatusCellDelegate
    func StatusCellDidSelctedPhoto(statusCell: StatusCell, photoIndex: Int) {
        print(statusCell.status?.largePicURLs![photoIndex])
        if statusCell.status?.largePicURLs == nil {
            return
        }
        //准备转场素材
        presentedImage.sd_setImageWithURL(statusCell.status?.largePicURLs![photoIndex])
        
        //当前的frame
       presentedImage.frame =  statusCell.PictureCellScreenFrame(photoIndex)
        
        //放大后的frame
       presentedImageFrame =  statusCell.cellFullScreenFrame(photoIndex)
        
        let vc = PhotoBrowserViewController(index: photoIndex, urls: (statusCell.status?.largePicURLs)!)
        //设置转场代理
        vc.transitioningDelegate = self
        //设置转场样式
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(vc, animated: true, completion: nil)
    }
    
    //定义临时展现的图片
    lazy var presentedImage = UIImageView()
    //定义展现的frame
    var presentedImageFrame = CGRectZero
    
    //MARK: - UITableviewDelegate
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return weiboArray?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let status = weiboArray![indexPath.row]
        let ID = StatusCell.selectCellIdentifier(status)
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! StatusCell
        //设置cell
        cell.status = status
        cell.photoDelegate = self
        if indexPath.row == (weiboArray?.count)! - 1 {
            PullRefreshFlag = true
            loadData()
        }
        
        return cell
    }
    
    //设置行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //取到对象
        let status = weiboArray![indexPath.row]
        //判断是否缓存了行高
        if rowHeightCache[status.id] != nil {
            return rowHeightCache[status.id]!
        }
        
        let ID = StatusCell.selectCellIdentifier(status)
        
        //默认为原创微博
        var cls: AnyClass = NormalCell.self
        
        //判断是否为转发微博
        if ID == XDRetweetCellReuseIdentifier {
            
            cls = RetweetedCell.self
        }
        //实例化cls
        let cell = cls.new() as! StatusCell
        
        //返回行高
        let height = cell.rowHeight(status)
        rowHeightCache[status.id] = height
        return height
        
    }
    
    /// 动画转场代理
    let popoverAnimator = PopoverAnimator()
    
    
    //扫一扫点击事件
    func QRcodeBtnClick() {
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        presentViewController(sb.instantiateInitialViewController()!, animated: true, completion: nil)
    }
    //标题按钮点击事件
    func titleButtonClicked() {
        let sb = UIStoryboard(name: "FriendGroup", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("FriendGroupSB")
        
        // 1. 设置`转场 transitioning`代理
        vc.transitioningDelegate = popoverAnimator
        // 2. 设置视图的展现大小
        let x = (view.bounds.width - 200) * 0.5
        popoverAnimator.presentFrame = CGRectMake(x, 56, 200, 300)
        // 3. 设置专场的模式 - 自定义转场动画
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc, animated: true, completion: nil)
    }

    //自定义导航栏
   private func setupNavgationBar() {
        //判断用户是否登录
    if sharedUserAccount == nil {
        return
    }
    //设置按钮
    navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", hightImageName: nil)

    navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", hightImageName: nil)
    let btn = navigationItem.rightBarButtonItem?.customView as! UIButton
    btn.addTarget(self, action: "QRcodeBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
    //设置标题
    let titleBtn = HomeTitleButton.button((sharedUserAccount?.name )!)
    
    titleBtn.addTarget(self, action: "titleButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
    navigationItem.titleView = titleBtn
    }
    
    private var PullRefreshFlag = false
    private var isPresented = false

}
extension HomeTableViewController: UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning {
    
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
         let viewKey = isPresented ? UITransitionContextToViewKey : UITransitionContextFromViewKey
        let targetView = transitionContext.viewForKey(viewKey)
        
        if targetView == nil {
            return
        }
        if isPresented {
            // 2. 添加 toView
            transitionContext.containerView()?.addSubview(targetView!)
            targetView!.alpha = 0
            
            // 2.1 添加临时图片
            transitionContext.containerView()?.addSubview(presentedImage)
            
            // 3. 动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                self.presentedImage.frame = self.presentedImageFrame
                }, completion: { (_) -> Void in
                    
                    self.presentedImage.removeFromSuperview()
                    targetView!.alpha = 1

                    // *** 告诉动画完成
                    transitionContext.completeTransition(true)
            })
        } else {
            // 2. 动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                targetView!.alpha = 0
                }, completion: { (_) -> Void in
                    targetView?.removeFromSuperview()
                    transitionContext.completeTransition(true)
            })
        }

    }
}
